package models

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"os"
)

var DB *gorm.DB
var err error

func Init() *gorm.DB {
	dsn := "root:EiMx6ahnrtL6S4cp@tcp(" + GetEnvDefault("DB_HOST", "127.0.0.1") + ":3306)/chirper?charset=utf8mb4&parseTime=True&loc=Local"
	DB, err := gorm.Open(mysql.Open(dsn), &gorm.Config{})

	if err != nil {
		fmt.Printf("db connect err:%v", err)
	}
	return DB
}

func GetEnvDefault(key, defVal string) string {
	val, ex := os.LookupEnv(key)
	if !ex {
		return defVal
	}
	return val
}